﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;

namespace Algorithms_10.Tools
{
    public class ImageScanner
    {

        public Point[] ScanBottom(Bitmap bmp, Color foreground, Color background)
        {
            int width = bmp.Width;
            int height = bmp.Height;
            BitmapData outputData = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
            int stride = outputData.Stride;
            Point[] scan = new Point[width];
            int pixelSize = 3;
            if (bmp.PixelFormat == PixelFormat.Format24bppRgb)
            {
                pixelSize = 24 / 8;
            }
            else if (bmp.PixelFormat == PixelFormat.Format32bppArgb)
            {
                pixelSize = 32 / 8;
            }
            bool pixelFound = false;
            unsafe
            {
                byte* optPnt = (byte*)outputData.Scan0;
                //begin at bottom left
                byte* beginRowPnt = optPnt + stride * (height - 1);
                for (int x = 0; x < width; x++)
                {
                    pixelFound = false;
                    byte* beginColumnPnt = beginRowPnt + (x * pixelSize);
                    for (int y = height; y > 0 && !pixelFound; y--)
                    {
                        byte* curPnt = beginColumnPnt - (stride * (height - y)) + 1;
                        if (curPnt[1] == 255)
                        {
                            scan[x] = new Point(x, y);
                            pixelFound = true;
                        }
                    }
                }
            }
            bmp.UnlockBits(outputData);

            return scan;
        }
    }
}
